package newtank.network.server.handler;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import newtank.data.TransDataSignal;
import newtank.data.assistant.SyncData;
import newtank.network.server.registry.ChannelRegistry;
import server.netty.GpcDataPackage;
import server.netty.NettyGpcRequestHandler;

/**
 * @author lijiahao
 * @since 2021/12/9
 */
public class MoveDataHandler extends AbstractDataHandler implements EnvironmentHandlerAware {

    private EnvironmentLoadDataHandler environmentLoadDataHandler;

    @Override
    public void handle(ChannelHandlerContext ctx, GpcDataPackage data) {
        if(this.environmentLoadDataHandler == null) {
            setEnvironmentLoadDataHandler(NettyGpcRequestHandler.getEnvironmentLoadDataHandler());
        }
        String sync = data.getRequestHeader(SyncData.SYNC_DATA);
        SyncData syncData = JSONObject.parseObject(sync, SyncData.class);
        this.environmentLoadDataHandler.update(data.getUnique(), syncData.getPosition(), syncData.getDirection(), syncData.getVersion());
        TransDataSignal transDataSignal = new TransDataSignal();
        transDataSignal.setUnique(data.getUnique());
        transDataSignal.setLength(data.getLength());
        transDataSignal.setContext(data.getContext());
        transDataSignal.setCode(data.getCode());
        transDataSignal.setStatus(data.getStatus());
        transDataSignal.filledData(data);
        ChannelRegistry.inform(transDataSignal);
    }

    @Override
    public void setEnvironmentLoadDataHandler(EnvironmentLoadDataHandler environmentLoadDataHandler) {
        this.environmentLoadDataHandler = environmentLoadDataHandler;
    }
}
